package com.tsxy.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsxy.common.APIResult;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.tsxy.service.IRoleService;
import com.tsxy.entity.Role;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 飞
 * @since 2022-02-17
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
    private IRoleService roleService;

    //新增或者修改
    @PostMapping
    public APIResult save(@RequestBody Role role){
        return APIResult.success(roleService.saveOrUpdate(role));
    }
    //根据id删除
    @DeleteMapping("/{id}")
    public APIResult delete(@PathVariable Integer id) {
        return APIResult.success(roleService.removeById(id));
    }
    //批量删除
    @PostMapping("/del/batch")
        public APIResult deleteBath(@RequestBody List<Integer> ids){
        return APIResult.success(roleService.removeByIds(ids));
    }
    //查询所有
    @GetMapping
    public APIResult findAll() {
        return APIResult.success(roleService.list());
    }
    //根据id查询
    @GetMapping("/{id}")
        public APIResult findOne(@PathVariable Integer id) {
        return APIResult.success(roleService.getById(id));
    }
    //分页查询
    @GetMapping("/page")
    public APIResult findPage(@RequestParam Integer pageNum,
                            @RequestParam Integer pageSize,
                              @RequestParam(defaultValue = "") String name    ) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if ( ! "".equals(name)){
            queryWrapper.like("name",name);
        }
        queryWrapper.orderByDesc("id");
        return APIResult.success(roleService.page(new Page<>(pageNum,pageSize), queryWrapper));
    }

    /**
     * 绑定角色和菜单的关系
     * @return
     */
    @PostMapping("/roleMenu/{roleId}")
    public APIResult postRoleMenu(@PathVariable("roleId") Integer roleId, @RequestBody List<Integer> menuids){
        roleService.setRoleMenu(roleId,menuids);
        return APIResult.success();
    }

    @GetMapping("/roleMenu/{roleId}")
    public APIResult getRoleMenu(@PathVariable("roleId") Integer roleId){
        List<Integer> list = roleService.getRoleMenu(roleId);
        return APIResult.success(list);
    }

}

